/*
 * Copyright (c) 2024-2025 LTC-CN. All rights reserved.
 * <p>
 * This file is part of the ltc-cn-springboot project.
 * <p>
 * ltc-cn-springboot is distributed under the terms of the MIT License.
 * For details, see the accompanying LICENSE file or visit:
 * <a href="https://www.ltc-cn.top/projects">...</a>
 */

package top.ltc_cn.springboot_tools.tools;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ltc-cn xiaoyangcc
 */
@Slf4j
public class DataToMapUtils {
    private DataToMapUtils() {} // 防止实例化

    /**
     * 将输入的数据转换为Map
     * @param data
     * @return
     */
    public static Map<String, Object> dataToMap(Object data) {
        try {
            if (data == null) {
                log.debug("data is null");
                return new HashMap<>();
            }

            Map<String, Object> map = new HashMap<>();
            if (data instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> typedMap = (Map<String, Object>) data;
                for (Map.Entry<String, Object> entry : typedMap.entrySet()) {
                    if (!(entry.getKey() instanceof String)) {
                        log.error("Failed to convert data to Map: Map keys must be of type String");
                        throw new IllegalArgumentException("Map keys must be of type String");
                    }
                }
                map.putAll(typedMap);
            } else if (data instanceof String) {
                map = JSON.parseObject((String) data, Map.class);
            } else if (data instanceof byte[]) {
                map = JSON.parseObject(new String((byte[]) data), Map.class);
            } else {
                log.error("Failed to convert data to Map: Unsupported data type: " + data.getClass().getName());
                throw new IllegalArgumentException("Unsupported data type: " + data.getClass().getName());
            }

            return map;
        } catch (Exception e) {
            log.error("Failed to convert data to Map", e);
            throw new IllegalArgumentException("Failed to convert data to Map: " + e.getMessage(), e);
        }
    }

}
